package main

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"math/rand"
	"peilian-api/app/global/databases/tables"
	"peilian-api/app/global/variable"
	_ "peilian-api/bootstrap"
	"time"
)

func InitMySQL() (*gorm.DB, error) {
	dsn := fmt.Sprintf(
		"%s:%s@tcp(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local&timeout=%s",
		variable.Config.Mysql.UserName,
		variable.Config.Mysql.PassWord,
		variable.Config.Mysql.Host,
		variable.Config.Mysql.Port,
		variable.Config.Mysql.DBName,
		variable.Config.Mysql.TimeOut,
	)
	DB, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger:                                   logger.Default.LogMode(logger.Info),
		DisableForeignKeyConstraintWhenMigrating: true,
	})
	if err != nil {
		return nil, err
	}
	sqlDB, _ := DB.DB()
	//设置数据库连接池参数
	sqlDB.SetMaxOpenConns(100) //设置数据库连接池最大连接数
	sqlDB.SetMaxIdleConns(20)  //连接池最大允许的空闲连接数，如果没有sql任务需要执行的连接数大于20，超过的连接会被连接池关闭。
	return DB, nil
}

func main() {
	db, _ := InitMySQL()
	//users := make([]tables.User, 0)
	//db.Where("agent_id=?", 6).Find(&users)
	//careers := make([]tables.Career, 0)
	//db.Find(&careers)
	//for _, u := range users {
	//	t := time.Date(2022, time.September, 20, rand.Intn(24), rand.Intn(60), rand.Intn(60), 0, time.UTC)
	//	randSub := rand.Intn(len(careers))
	//	career := careers[randSub]
	//	session := tables.Session{
	//		UserID:     u.ID,
	//		CareerID:   career.ID,
	//		UserPhoto:  "",
	//		Status:     1,
	//		Url:        "",
	//		TotalScore: rand.Float64(),
	//		School:     u.School,
	//		Academy:    u.Academy,
	//		Profession: u.Profession,
	//		Grade:      u.Grade,
	//		UserName:   u.Name,
	//		UserPhone:  u.Phone,
	//		CareerName: career.Name,
	//		FinishAt:   t,
	//	}
	//	db.Create(&session)
	//
	//}
	sessions := make([]tables.Session, 0)
	db.Where("school=?", "北京工商大学").Find(&sessions)
	for _, s := range sessions {
		s.CreatedAt = time.Date(2022, time.September, rand.Intn(7)+13, rand.Intn(24), rand.Intn(60), rand.Intn(60), 0, time.UTC)
		db.Save(&s)
	}
}
